var gulp = require('gulp');
var sass = require('gulp-sass');
var rename = require('gulp-rename');
var cleanCss = require('gulp-clean-css');
var useref = require('gulp-useref');
var gulpif = require('gulp-if');
var uglify = require('gulp-uglify');
var ngAnnotate = require('gulp-ng-annotate');
var concat = require('gulp-concat');
var notify = require("gulp-notify");
var templateCache = require('gulp-angular-templatecache');
var htmlmin = require('gulp-htmlmin');
var autoprefix = require('gulp-autoprefixer');
var sourcemaps = require('gulp-sourcemaps');
var minimist = require('minimist');
var replace = require('gulp-replace');
var rev = require('gulp-rev');
var revReplace = require('gulp-rev-replace');
var filter = require('gulp-filter');


var knownOptions = {
    string: 'env',
    default: {env: process.env.NODE_ENV || 'prd', lang: 'zh_CN'}
};
var options = minimist(process.argv.slice(2), knownOptions);

// 源代码目录
var src_paths_index = {
    ico: ['src/*.ico'],
    sass: ['src/index/scss/*.scss'],
    css: ['src/index/css/*.css'],
    file: ['src/index.html']

};

// 中间目录（sass实时编译为css）
var dest_paths_index = {
    sass: 'src/index/css/',
    directive_template: 'src/index/scripts/'
};

// 发布目录（build打包结果）
var dist_paths_index = {
    root: 'dist/' + options.lang + '/',
    index: 'dist/' + options.lang + '/index/'
};

gulp.task('index-watch', false, function () {
    gulp.watch(src_paths_index.sass, ['index-sass']);
});

gulp.task('index-sass', false, function (done) {
    gulp.src(src_paths_index.sass)
        .pipe(sass())
        .on('error', sass.logError)
        .pipe(autoprefix({ browsers: ['last 2 versions'] }))
        .pipe(gulp.dest(dest_paths_index.sass))
        .on('end', done);
});

gulp.task('index-ico', false, function (done) {
    gulp.src(src_paths_index.ico)
        .pipe(gulp.dest(dist_paths_index.root))
        .on('end', done);
});


gulp.task('build-index-html', '首页html编译任务', ['index-sass','index-ico'], function(done) {
    gulp.src(src_paths_index.file)
        .pipe(gulpif(options.lang === 'en_US', replace(/zh-CN/g, 'en-US')))
        .pipe(useref())
        .pipe(gulpif('*.css', cleanCss()))
        .pipe(gulpif('*.css', gulp.dest(dist_paths_index.root) ))
        .pipe(gulpif('*.js', sourcemaps.init()))
        .pipe(gulpif('*.js', ngAnnotate({
            single_quotes: true
        })))
        .pipe(gulpif('*.js', uglify()))
        .pipe(gulpif('*.js', sourcemaps.write('./', {
            sourceRoot: './'
        })))
        .pipe(gulpif('*.map', gulp.dest(dist_paths_index.root)))
        .pipe(gulpif('*.js', gulp.dest(dist_paths_index.root)))
        .pipe(gulpif('*.html', gulp.dest(dist_paths_index.root)))
        .on('end', done);
});

gulp.task('task-index', '首页模块监视任务', ['index-watch'], function () {

});

gulp.task('build-index', '首页编译任务', ['build-index-html'], function () {

});